package com.learn.algorithm_1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 添加一个元素后，返回第k大的元素
 */
public class KthLargest {

    public static void main(String[] args) {
        KthLargest kthLargest = new KthLargest(3, new int[]{4,5,8,2});
        System.out.println(kthLargest.add(3));// returns 4
        System.out.println(kthLargest.add(5));// returns 5
        System.out.println(kthLargest.add(10));// returns 5
        System.out.println(kthLargest.add(9));// returns 8
        System.out.println(kthLargest.add(4));// returns 8
    }

    private int k;
    private int[] nums;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        this.nums = nums;
    }

    public int add(int val) {
        List<Integer> list = new ArrayList<>();
        int[] temp = new int[nums.length + 1];
        for (int i = 0; i < nums.length; i++) {
            list.add(nums[i]);
            temp[i] = nums[i];
        }
        list.add(val);
        temp[nums.length] = val;
        this.nums = temp;
        Collections.sort(list);
        if(list.size() >= k){
            return list.get(list.size() -k);
        } else{
            return -1;
        }
    }

}

